# -*- coding: utf-8 -*-
"""
Markdown解析器
"""

import re
from typing import Any, Dict, List, Tuple
from pathlib import Path


class MarkdownParser:
    """Markdown文档解析器"""

    def __init__(self, scene_level: int = 2):
        """
        初始化解析器

        Args:
            scene_level: 场景标题层级
        """
        self.scene_level = scene_level

    def parse(self, md_text: str) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:
        """
        解析Markdown文本为场景数据

        Args:
            md_text: Markdown文本

        Returns:
            (元数据, 场景列表)
        """
        # 移除代码块
        md = self._strip_code_blocks(md_text)

        lines = md.splitlines()
        scenes = []
        cur_title = None
        cur_buf = []
        first_h1 = None

        def flush_scene():
            nonlocal cur_title, cur_buf
            text = " ".join([t.strip() for t in cur_buf if t.strip()]).strip()
            if cur_title or text:
                if not text and cur_title:
                    text = cur_title
                scene = {
                    "id": f"scene-{len(scenes)+1:03d}",
                    "title": (cur_title or "").strip(),
                    "narration": text,
                }
                scenes.append(scene)
            cur_title = None
            cur_buf = []

        for raw in lines:
            m = re.match(r"^(#{1,6})\s+(.*)$", raw)
            if m:
                level = len(m.group(1))
                title = m.group(2).strip()
                if level == 1 and not first_h1:
                    first_h1 = title
                if level <= max(1, int(self.scene_level)):
                    flush_scene()
                    cur_title = title
                    continue

            # 列表项保持为文本
            if raw.strip().startswith(("-", "*", "+")):
                cur_buf.append(raw.strip())
            else:
                cur_buf.append(raw)

        flush_scene()

        meta = {
            "title": first_h1 or "Generated Video",
            "language": "zh-CN",
        }

        data = {"version": "1.0", "meta": meta, "scenes": scenes}

        return data, scenes

    def _strip_code_blocks(self, md: str) -> str:
        """移除代码块"""
        return re.sub(r"```[\s\S]*?```", "", md, flags=re.MULTILINE)
